package com.hjqjl.androidutils.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Window;
import android.widget.TextView;

import com.hjqjl.androidutils.R;

import java.lang.ref.WeakReference;

/**
 * 旋转加载中dialog
 * DialogLoading.showLoading(this);
 * DialogLoading.stopLoading();
 */
public class DialogLoading extends BaseDialog {
    private WeakReference<Context> mContext;
    private volatile static DialogLoading instance;

    private TextView mTextMessage;
    private CharSequence mMessage;

    private DialogLoading(Context context, CharSequence message) {
        super(context);
        mContext = new WeakReference<>(context);
        mMessage = message;
    }

    private void setMessage(CharSequence message) {
        mTextMessage.setText(message);
    }

    public static synchronized void showLoading(Context context) {
        showLoading(context, "加载中...");
    }

    public static synchronized void showLoading(Context context, CharSequence message) {
        showLoading(context, message, true);
    }

    public static synchronized void showLoading(Context context, CharSequence message, boolean cancelable) {
        if (instance != null && instance.isShowing()) {
            instance.dismiss();
        }

        if (!(context instanceof Activity)) {
            return;
        }
        instance = new DialogLoading(context, message);
        instance.setCancelable(cancelable);

        if (instance != null && !instance.isShowing() && !((Activity) context).isFinishing()) {
            instance.show();
        }
    }

    public static synchronized void changeMessage(CharSequence message) {
        if (instance != null) {
            instance.setMessage(message);
        }
    }

    public static synchronized void stopLoading() {
        if (instance != null && instance.isShowing()) {
            instance.dismiss();
        }
        instance = null;
    }

    public static boolean isLoading() {
        return instance != null && instance.isShowing();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//去掉白色背景,设置对话框背景透明
            setContentView(R.layout.loading);
            mTextMessage = (TextView) findViewById(R.id.tv_text);
            if (!TextUtils.isEmpty(mMessage)) {
                mTextMessage.setText(mMessage);
            }
        }
        setCanceledOnTouchOutside(false);
    }
}